package br.pucrio.inf.aaaong.controllers;

import java.util.List;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.pucrio.inf.aaaong.models.domain.facade.PreInscricaoInsertFromFormFaultTolerant;
import br.pucrio.inf.aaaong.models.domain.form.beans.PreInscricaoFormBean;
import br.pucrio.inf.aaaong.models.domain.form.fields.PreInscricaoFields;
import br.pucrio.inf.aaaong.models.form.errors.FormError;

@Resource
@Path("/pre-inscritos")
public class PreInscritosController {
	private final Result result;
	private PreInscricaoInsertFromFormFaultTolerant insertFormFacade;
	
	public PreInscritosController(Result result, PreInscricaoInsertFromFormFaultTolerant insertFormFacade) {
		this.result = result;
		this.insertFormFacade = insertFormFacade;
	}
	
	@Get("/novo")
	public void novo() {
		addFormDependenciesToResult();
	}
	
	@Post("/")
	public void criar(PreInscricaoFormBean form) {
		List<FormError> errors = insertFormFacade.insert(form);
		
		if (errors.isEmpty()) {
			result.include("noticeMessage", "Pré-inscrito foi criado com sucesso.");
			result.redirectTo(PreInscritosController.class).novo();
		} else {
			result.include("errors", errors);
			result.include("form", form);
			addFormDependenciesToResult();
			result.of(PreInscritosController.class).novo();
		}
	}
	
	private void addFormDependenciesToResult() {
		result.include("turnoOptions", PreInscricaoFields.TURNO_ESCOLAR.getOptions());
		result.include("nivelEscolarOptions", PreInscricaoFields.NIVEL_ESCOLAR.getOptions());
	}
}
